package Midium;

import java.util.ArrayList;
import java.util.List;

//49.字母异位词分组
public class Solution49 {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> resList = new ArrayList<>();
        for (String str : strs) {
            boolean valid = false;//true代表已经放到resList中了，false代表我要开辟一个新的list，包含此str，放入到resList中
            for (List<String> list : resList) {
                for (String s : list) {
                    if (equales(s, str)) {
                        list.add(str);
                        valid = true;
                        break;
                    }
                }
                if (valid)
                    break;
            }
            if (!valid) {
                List<String> newList = new ArrayList<>();
                newList.add(str);
                resList.add(newList);
            }
        }
        return resList;
    }

    public boolean equales(String a, String b) {
        //判断两个字符串是否是异位词
        if (a.length() != b.length())
            return false;
        for (int i = 0; i < b.length(); i++) {
            char c = b.charAt(i);
            //把一个char转换为String需要使用Character
            String substr = Character.toString(c);
            if (!a.contains(substr)) {
                return false;
            }
            //如果a里包含该字符，则将a去掉该字符
            int j = a.indexOf(c);
            a=a.substring(0,j)+a.substring(j+1,a.length());
        }
        return true;
    }

    public static void main(String[] args) {
        Solution49 s49 = new Solution49();
        s49.groupAnagrams(new String[]{"ddg","dgg"});
    }
}
